package ltd.followkba.task;

import android.graphics.Bitmap;

import com.kcbsdk.AFileBase;
import com.kcbsdk.MyManage.AUserFileType;
import com.kcbsdk.MyWorks.AAccountType;
import com.kcbsdk.MyWorks.AFileInfo;
import com.kcbsdk.MyWorks.AGiftBean;
import com.kcbsdk.MyWorks.AKclFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;

import ltd.advskin.base.KcListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.utils.CLyricsFile;
import ltd.advskin.utils.SysBitmap;
import ltd.advskin.utils.SysUtils;
import ltd.followkba.MAPP;
import ltd.followkba.MDBS;
import ltd.followkba.W;
import main.CApiUtils;
import main.MAPI;

import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyUtils;

public class EditUtils {

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;

    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }
    public BAppUser getUserInfo(int worksType, String userIdS){
        return getUserInfo(worksType, userIdS, AUserFileType.IMG_SMALL);
    }
    public BAppUser getUserInfo(int worksType, String userIdS, AUserFileType aUserFileType){
        BAppUser bAppUser = null;
        if (worksType < 32) {
            bAppUser = App32.getUserInfo(userIdS);
            if (bAppUser != null) {
                bAppUser.HeadFile = App32.downloadHeadFile(aUserFileType, bAppUser, true);
            }
        }else if (worksType == 33 || worksType == 49) {
            bAppUser = App33.getUserInfo(userIdS);
            if (bAppUser != null) {
                App33.downloadHeadFile(aUserFileType, bAppUser, true);
            }

    }else if (worksType == 39){
            bAppUser = App39.getUserInfo(userIdS);
            if (bAppUser != null) {
                bAppUser.HeadFile = String.format("%sH28_%s.jpg", MRAM.gsCachePath, bAppUser.UserIdS);
                downloadPhoto(false, 0, 0, bAppUser.HeadUrl, bAppUser.HeadFile);
            }
        }
        return bAppUser;
    }
    public BAppWorks getWorksInfo(int worksType, String userIdS, String worksIdS){
        BAppWorks bAppWorks = null;
//        App33 app33 = MAPP.mAccount33;
//        App32 app32 = MAPP.mKcApp32;
        if ((worksType == 33 || worksType == 49)) {
            bAppWorks = App33.getWorksInfo(userIdS, worksIdS);
        }else if (worksType < 32){
            bAppWorks = App32.getWorksInfo(userIdS, worksIdS);
        }
        if (bAppWorks != null) {
            bAppWorks.WorksType = (byte) worksType;
            bAppWorks.UserIdS = userIdS;
//            bAppWorks.Tick = System.currentTimeMillis();
        }
        return bAppWorks;
    }
    public String downloadUrlFile(String fileUrl, String fileName){
        if (MAPI.IS_FILE_DONE(fileName)){
            return "ok";
        }
        if (fileUrl != null && fileName != null) {
            SysUtils sysUtils = new SysUtils();
            String result = sysUtils.getUrlFile(fileUrl, fileName);
            int length = MAPI.STRING_DEC32(result);
            if (length > 0 && length == MAPI.GET_FILE_LENGTH(fileName)) {
                MAPI.SET_FILE_DONE(fileName);
                return "ok";
            }else {
                return "下载出错 "+result;
            }
        }
        return null;
    }
    public String downloadLyricFile(String fileUrl, String fileName){
        if (MAPI.IS_FILE_DONE(fileName)){
            return "ok";
        }
        if (fileUrl != null && fileName != null) {
            String lyricFile = fileName + ".lrc";
            SysUtils sysUtils = new SysUtils();
            String result = sysUtils.getUrlFile(fileUrl, lyricFile);
            if ("error,4".equals(result)) {
                fileUrl = fileUrl + "e";
                result = sysUtils.getUrlFile(fileUrl, lyricFile);
            }
            int length = MAPI.STRING_DEC32(result);
            if (length > 0 && length == MAPI.GET_FILE_LENGTH(lyricFile)) {
                CLyricsFile cLyricsFile = new CLyricsFile();
                lyricFile = cLyricsFile.checkLocalFile(lyricFile);
                MLOG(String.format("downloadLyricFile C %s %s", MAPI.GET_FILE_LENGTH(lyricFile), lyricFile));
                if (MAPI.CONVERT_KCL_FILE(lyricFile, fileName, 0)) {                   // 将其他文件格式的文件，转成我们用的Kcl文件
                    MLOG(String.format("downloadLyricFile D %s -> %s(%s)", MAPI.GET_FILE_LENGTH(lyricFile), MAPI.GET_FILE_LENGTH(fileName), fileName));
                    MAPI.SET_FILE_DONE(fileName);
                    return "ok";
                }else {
                    return "下载出错 "+result;
                }
            }else {
                return "下载出错";
            }

        }
        return null;
    }
    public String downloadPhoto(boolean mustOver, int width, int height, String fileUrl, String fileName){
        if (MAPI.IS_FILE_DONE(fileName)){
            return "ok";
        }
        if (fileUrl != null && fileName != null){
            SysUtils sysUtils = new SysUtils();
            String result = sysUtils.getUrlFile(fileUrl, fileName);
            if ("error,4".equals(result)) {
                fileUrl = fileUrl.replace(".jpg", "_640_640.jpg");
                result = sysUtils.getUrlFile(fileUrl, fileName);
            }
            int length = MAPI.STRING_DEC32(result);
            if (length > 0 && length == MAPI.GET_FILE_LENGTH(fileName)) {
                if (width > 0 && height > 0){                         // 需要指定宽高
                    SysBitmap sysBitmap = new SysBitmap();
                    int g4Local_1 = sysBitmap.getBitmapSize(fileName);
                    int tureW = g4Local_1 >> 16;
                    int tureH = g4Local_1 & 0xffff;
                    MLOG(String.format("downloadPhoto B %sx%s %sx%s %s", tureW, tureH, width, height, fileName));
                    if (mustOver){                      // 必须要大于
                        if (tureW < width || tureH < height){         // 必须要大于指定的宽高
                            return String.format("图片规格不适合%sx%s(%sx%s)", tureW, tureH, width, height);
                        }
                    }else {
                        int scale1 = (int)((float)width / (float)height);
                        int scale2 = (int)((float)tureW / (float)tureH);
                        if (scale1 == scale2){                          // 比例相同的
                            MAPI.SET_FILE_DONE(fileName);
                            return "ok";
                        }
                    }
                    MLOG(String.format("downloadPhoto C %sx%s %sx%s %s", tureW, tureH, width, height, fileName));
                    Bitmap bitmap = sysBitmap.getReqBitmap(width, height, 0, 0, 0, 0, 0, fileName);
                    if (sysBitmap.saveBitmapFile(bitmap, fileName)) {
                        MAPI.SET_FILE_DONE(fileName);
                        return "ok";
                    }
                }else {
                    MAPI.SET_FILE_DONE(fileName);
                    return "ok";
                }
                return result;
            }else {
                return "下载出错 "+result;
            }
        }
        return null;
    }

    public String getLyricLine(int line, String fileName){
        AKclFile aKclFile = MAPI.READ_KCL_FILE(fileName);
        if (aKclFile != null && aKclFile.Lines != null){
            int start;
            if (line < (aKclFile.Lines.length / 4)){            // 需要的行数小于1/4
                start = aKclFile.Lines.length / 4;              // 使用后3/4。开始部分可能有其他的不是歌词的文字
            }else {                                         // 取全部
                start = 0;
            }
            StringBuffer stringBuffer = new StringBuffer();
            for (; start < aKclFile.Lines.length; start++){
                if (checkKeyword(aKclFile.Lines[start].Text)){
                    stringBuffer.append(aKclFile.Lines[start].Text);
                    stringBuffer.append(" ");
                    if (--line == 0){
                        break;
                    }
                }
            }
            return stringBuffer.toString();
        }
        return null;
    }
    private boolean checkKeyword(String text){
        if (text != null) {
            String[] texts = {"歌曲", "歌手", "制作", "作词", "作曲", "QQ", "WX", "微信",};
            for (int index = 0; index < texts.length; index++) {
                if (text.indexOf(texts[index]) >= 0) {
                    return false;
                }
            }
        }
        return true;
    }



    public void getAndSaveBDbsAccountInfo(KcListener kcListener){
        MLOG(String.format("AccountNameAf0: %s(%s)", MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.WorksType));
        new TaskFree(kcListener, new TaskFree.Listener() {
            @Override
            public void onMessage(boolean isThread, Object object) {
                if (isThread){
                    MAPP.MTOAST("正在获取信息...");
                    MLOG(String.format("AccountNameAf1: %s(%s)", MAPP.mBDbsAccount.AccountName, MAPP.mBDbsAccount.WorksType));
                    BAppUser bAppUser = getUserInfo(MAPP.mBDbsAccount.WorksType, MAPP.mBDbsAccount.UserIdS);
                    MLOG(String.format("AccountNameAf2: %s(%s)", MAPP.mBDbsAccount.AccountName, bAppUser));
                    if (bAppUser != null) {
                        MDBS.setBAppUser(bAppUser);
                        MAPP.mBDbsAccount.UserName = bAppUser.UserName;
                        MAPP.mBDbsAccount.HeadFile = bAppUser.HeadFile;
                    }
                    RunUtils.saveBDbsAccount(MAPP.mBDbsAccount);

                    int worksType = MAPP.mBDbsAccount.WorksType;
                    for (int index = 0; index < MAPP.mWorksType.length; index++) {
                        byte appType = -1;
                        if (worksType == 33 && MAPP.mWorksType[index] == 33) {          // 查找相同类型的账号
                            appType = 49;
                        }else if (worksType == 49 && MAPP.mWorksType[index] == 49) {
                            appType = 33;
                        }else if (worksType < 0x20 && MAPP.mWorksType[index] < 0x20) {
                            appType = MAPP.mWorksType[index];
                        }
                        if (appType >= 0) {                // 同时更新信息到其他相同的AppType
//                            MAPP.MTOAST("正在获取信息...");
                            BDbsAccount bDbsAccount = MDBS.getBDbsAccount(appType, MAPP.mBDbsAccount.AccountName);
                            if (bDbsAccount != null && bDbsAccount.WorksType != worksType){
                                copyBDbsAccount(bDbsAccount, MAPP.mBDbsAccount);
                                if (bAppUser != null) {
                                    MLOG(String.format("AccountNameAh: %s(%s)", MAPP.mBDbsAccount.AccountName, appType));

                                    MDBS.setBAppUser(bAppUser);
                                    bDbsAccount.UserName = bAppUser.UserName;
                                    bDbsAccount.HeadFile = bAppUser.HeadFile;
                                }
                                RunUtils.saveBDbsAccount(bDbsAccount);
                            }
                        }
                    }
                    if (bAppUser == null) {
                        MLOGE(String.format("changeUserA4 %s %s", MAPP.mBDbsAccount.WorksType, MAPP.mBDbsAccount.UserIdS));
                    }
                    return;
                }
                if (object != null) {
                    KcListener kcListener = (KcListener)object;
                    kcListener.onMessage(isThread);
                }
            }
        });
    }
    public int getCrcSum5(String accountName){
        if (accountName != null) {
            SysUtils sysUtils = new SysUtils();
            String md5 = sysUtils.getStringMd5(accountName);
            int crcSum5 = MAPI.GET_SPEC_WORD_CHECKSUM(md5.getBytes().length, 0, md5.getBytes());
            crcSum5 |= accountName.charAt(0) << 24;
            crcSum5 |= accountName.charAt(accountName.length() - 1) << 16;
//            MLOG(String.format("getCrcSum5A %08x %s", crcSum5, accountName));
            return crcSum5;
        }
        return 0;
    }

    public void copyBDbsAccount(BDbsAccount target, BDbsAccount source){
        target.UserName = source.UserName;
        target.HeadFile = source.HeadFile;
        target.LoginFlag = source.LoginFlag;
        target.UserID = source.UserID;
        target.UserIdS = source.UserIdS;
        target.UserName = source.UserName;
        target.Status = source.Status;
        target.SearchUser = source.SearchUser;
        target.SelectWorksType = source.SelectWorksType;
        target.CloneHead = source.CloneHead;                // 克隆账号的用户头像
        target.CloneUserIdS = source.CloneUserIdS;             // 克隆账号的用户ID
        target.CloneUserName = source.CloneUserName;             // 克隆账号的用户名字
        target.CloneAppType = source.CloneAppType;                // 克隆账号的App类型
    }

    public boolean waitWriteLock(String text){
        while (!MAPP.threadStop) {
            if (MAPP.mBDbsAccount.WorksType < 32) {
                if (MAPP.lockWrite32(text)) {
                    return true;
                }
            }else if (MAPP.mBDbsAccount.WorksType == 33) {
                if (MAPP.lockWrite33(text)) {
                    return true;
                }
            }
            MSLEEP(100);
        }
        return false;
    }
    public void clearWriteLock(){
        if (MAPP.mBDbsAccount.WorksType < 32) {
            MAPP.lockWrite32(null);
        }else if (MAPP.mBDbsAccount.WorksType == 33) {
            MAPP.lockWrite33(null);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public void logBRankInfo(){
        String text = "";
        for (int index = 0; index < MAPP.mKcBRankInfo.length; index++){
            text += MAPP.mKcBRankInfo[index].Name + " ";
        }
        MLOG(String.format("QueueA logBRankInfo length %s %s", MAPP.mKcBRankInfo.length, text));
    }
    public void logAGiftBean(){
        String text = "";
        for (int index = 0; index < MAPP.mKcAGiftBean.length; index++){
            text += MAPP.mKcAGiftBean[index].GiftName + " ";
        }
        MLOG(String.format("QueueA logAGiftBeann %s %s", MAPP.mKcAGiftBean.length, text));
    }
    public void makeBRankInfo(List<AFileBase> rankArea){
        List<BRankInfo> bRankInfos = new ArrayList<>();
        List<String> provinces = mMyUtils.getAreaProvinceList();
        int leng1 = provinces != null ? provinces.size() : 0;
        for (int count1 = 0; count1 < leng1; count1++){
            String province = provinces.get(count1);
            if (!MAPI.isEmpty(province)) {
                List<String> citys = mMyUtils.getAreaCityList(province);
                int leng2 = citys != null ? citys.size() : 0;
                for (int count2 = 0; count2 < leng2; count2++) {
                    String city = citys.get(count2);
                    if (!MAPI.isEmpty(city)) {
//                                MLOG(String.format("QueueA readGiftRank province %s city:%s", province, city));
                        List<String> regionss = mMyUtils.getAreaRegionsList(province, city);
                        int leng3 = regionss != null ? regionss.size() : 0;
                        if (leng3 > 0) {
                            for (int count3 = 0; count3 < leng3; count3++) {
                                String regions = regionss.get(count3);
                                addAreaRankData(province, city, regions, bRankInfos);                  // 转换为榜数据
                            }
                        }else {
                            addAreaRankData(province, city, "", bRankInfos);
                        }
                    }
                }
            }
        }
        MAPP.mKcBRankInfo = new BRankInfo[2 + bRankInfos.size()];
        MAPP.mKcBRankInfo[0] = new BRankInfo();
        MAPP.mKcBRankInfo[0].AreaData = 0xfffe;
        MAPP.mKcBRankInfo[0].UserID = mMyUtils.getSpecAccount(AAccountType.ID_RANK_COUNTRY).UserID;
        MAPP.mKcBRankInfo[0].Name = "全国";
        MAPP.mKcBRankInfo[1] = new BRankInfo();
        MAPP.mKcBRankInfo[1].AreaData = 0xfffd;
        MAPP.mKcBRankInfo[1].UserID = mMyUtils.getSpecAccount(AAccountType.ID_RANK_NEW).UserID;
        MAPP.mKcBRankInfo[1].Name = "新作";
        int length = rankArea.size();
        for (int index = 2; index < MAPP.mKcBRankInfo.length; index++){
            MAPP.mKcBRankInfo[index] = new BRankInfo();
            MAPP.mKcBRankInfo[index].AreaData = bRankInfos.get(index - 2).AreaData;
            MAPP.mKcBRankInfo[index].Name = bRankInfos.get(index - 2).Name;
            for (int count = 0; count < length; count++) {
                AFileBase aFileBase = rankArea.get(count);
                if (MAPP.mKcBRankInfo[index].AreaData == aFileBase.FileID) {
                    MAPP.mKcBRankInfo[index].UserID = aFileBase.UserID;
                    break;
                }
            }
        }
        List<BRankInfo> lists = new ArrayList<>();
        for (int index = 0; index < MAPP.mKcBRankInfo.length; index++){
            if (MAPP.mKcBRankInfo[index].UserID > 0) {
                lists.add(MAPP.mKcBRankInfo[index]);
            }else {
                MLOGE(String.format("QueueA readGiftRank UserID Error %s %04x", MAPP.mKcBRankInfo[index].Name, MAPP.mKcBRankInfo[index].AreaData));
            }
        }
        MDBS.setRankGiftList(false, (List)lists);
        logBRankInfo();
    }
    public void makeGiftBean(List<AFileBase> giftIcon){
        List<AGiftBean> aGiftBeans = new ArrayList<>();
        int length = giftIcon.size();
        for (int index = 0; index < length; index++) {
            AFileBase aFileBase = giftIcon.get(index);
            if (aFileBase != null) {
                AGiftBean aGiftBean = new AGiftBean();
                aGiftBean.UserID = aFileBase.UserID;
                aGiftBean.FileID = aFileBase.FileID;
                AFileInfo aFileInfo = null;
                long timeout = System.currentTimeMillis();
                while (aFileInfo == null || MAPI.isEmpty(aGiftBean.GiftName)){
                    aFileInfo = MSKIN.getAFileInfo(aFileBase);
                    aGiftBean.GiftName = mMyUtils.getFileName(aFileBase);    // 礼物名称
                    MSLEEP(100);
                    if ((System.currentTimeMillis() - timeout) > 5000){
                        MLOGE(String.format("QueueA readGiftRank E %s_%04x", aGiftBean.UserID, aGiftBean.FileID));
                        break;
                    }
                }
                if (aFileInfo != null) {
                    aGiftBean.GiftValue = aFileInfo.MusicID0;   // 礼物价格
                    aGiftBean.GiftHot = aFileInfo.HotValue;     // 礼物热度
                    aGiftBean.GiftKeep = aFileInfo.MusicID1;    // 礼物保持时间
                    aGiftBean.Index = aFileInfo.AuxID;       // 礼物索引升序
                    aGiftBeans.add(aGiftBean);
//                            MLOG(String.format("QueueA readGiftRank C %s_%s_%04x_%s_%s", index, aGiftBean.UserID, aGiftBean.FileID, aGiftBean.GiftName, aGiftBeans.size()));
                }
            }
        }
        Collections.sort(aGiftBeans, new Comparator<AGiftBean>() {
            public int compare(AGiftBean info1, AGiftBean info2) {
                if (info1 != null && info2 != null) {
                    return (info1.Index - info2.Index);  // 升序
                }
                return 0;
            }
        });
        MAPP.mKcAGiftBean = aGiftBeans.toArray(new AGiftBean[aGiftBeans.size()]);
    }
    private void addAreaRankData(String province, String city, String regions, List<BRankInfo> bRankInfos){
        BRankInfo bRankInfo = new BRankInfo();
        int areaData = mMyUtils.getAreaRankData(province, city, regions);
        bRankInfo.Name = mMyUtils.getAreaDataRankName(areaData);
        bRankInfo.AreaData = mMyUtils.getAreaDataRankCode(areaData);            // 真实的榜数据
//if ("深圳市".equals(city)){//深圳广东
//    MLOG(String.format("QueueA readGiftRank mKcBRankInfo %s_%s_%s_%04x %04x %04x", province, city, regions, bRankInfo.Name, areaData, bRankInfo.AreaData));
//}

        int length = bRankInfos.size();
        for (int index = 0; index < length; index++){
            if (bRankInfo.Name.equals(bRankInfos.get(index).Name)){
                return;
            }
        }
        bRankInfos.add(bRankInfo);
    }

}
